package com.gzc.just.play.last.war.sceneserver.service;

import com.gzc.just.play.last.war.sceneserver.battle.manager.EnhancedBattleSessionManager;
import com.gzc.just.play.last.war.sceneserver.battle.model.BattleInfo;
import com.gzc.just.play.last.war.sceneserver.battle.model.BattleUserInfo;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 战斗消息处理服务
 * 负责处理战斗相关的消息，如创建战斗、加入战斗、离开战斗等
 */
@Service
public class BattleMessageService {
    private static final Logger logger = LoggerFactory.getLogger(BattleMessageService.class);
    
    @Autowired
    private EnhancedBattleSessionManager enhancedBattleSessionManager;
    
    // 消息ID常量
    private static final int CREATE_BATTLE = 1001;
    private static final int JOIN_BATTLE = 1002;
    private static final int LEAVE_BATTLE = 1003;
    private static final int START_BATTLE = 1004;
    
    /**
     * 处理创建战斗消息
     */
    public boolean handleCreateBattle(ChannelHandlerContext ctx, Long userId, int messageId, byte[] messageData) {
        try {
            // 从消息中解析战斗参数（这里是示例实现）
            String battleName = extractStringFromMessage(messageData, 8);
            BattleInfo.BattleType battleType = BattleInfo.BattleType.PVP; // 默认类型
            Integer mapId = extractIntFromMessage(messageData, 40); // 假设在40位置
            Integer maxPlayers = extractIntFromMessage(messageData, 44); // 假设在44位置
            
            if (maxPlayers == null || maxPlayers <= 0) {
                maxPlayers = 10; // 默认最大玩家数
            }
            
            // 创建战斗
            BattleInfo battle = enhancedBattleSessionManager.createBattle(battleType, mapId, maxPlayers);
            
            // 创建用户信息
            String playerName = "Player" + userId;
            BattleUserInfo userInfo = new BattleUserInfo();
            userInfo.setUserId(userId);
            userInfo.setNickname(playerName);
            
            // 将创建者加入战斗
            boolean joinSuccess = enhancedBattleSessionManager.addPlayerToBattle(battle.getBattleId(), userInfo);
            
            if (joinSuccess) {
                // 发送创建成功响应
                sendCreateBattleResponse(ctx, battle.getBattleId(), true, "Battle created successfully");
                logger.info("Player {} created and joined battle: {}", userId, battle.getBattleId());
                return true;
            } else {
                // 发送创建失败响应
                sendCreateBattleResponse(ctx, -1, false, "Failed to join battle after creation");
                logger.error("Player {} failed to join battle after creation: {}", userId, battle.getBattleId());
                return false;
            }
        } catch (Exception e) {
            logger.error("Error handling create battle message for user: " + userId, e);
            sendCreateBattleResponse(ctx, -1, false, "Error creating battle");
            return false;
        }
    }
    
    /**
     * 处理加入战斗消息
     */
    public boolean handleJoinBattle(ChannelHandlerContext ctx, Long userId, Long battleId, int messageId, byte[] messageData) {
        try {
            if (battleId == null) {
                sendJoinBattleResponse(ctx, false, "Invalid battle ID");
                return false;
            }
            
            // 获取玩家名称
            String playerName = extractStringFromMessage(messageData, 8);
            if (playerName == null || playerName.isEmpty()) {
                playerName = "Player" + userId;
            }
            
            // 创建用户信息
            BattleUserInfo userInfo = new BattleUserInfo();
            userInfo.setUserId(userId);
            userInfo.setNickname(playerName);
            
            // 将玩家加入战斗
            boolean success = enhancedBattleSessionManager.addPlayerToBattle(battleId, userInfo);
            
            if (success) {
                // 发送加入成功响应
                sendJoinBattleResponse(ctx, true, "Joined battle successfully");
                logger.info("Player {} joined battle: {}", userId, battleId);
                return true;
            } else {
                // 发送加入失败响应
                sendJoinBattleResponse(ctx, false, "Failed to join battle");
                logger.warn("Player {} failed to join battle: {}", userId, battleId);
                return false;
            }
        } catch (Exception e) {
            logger.error("Error handling join battle message for user: " + userId + ", battle: " + battleId, e);
            sendJoinBattleResponse(ctx, false, "Error joining battle");
            return false;
        }
    }
    
    /**
     * 处理离开战斗消息
     */
    public boolean handleLeaveBattle(ChannelHandlerContext ctx, Long userId, int messageId, byte[] messageData) {
        try {
            // 获取用户所在的战斗
            BattleInfo battle = enhancedBattleSessionManager.getUserBattleInfo(userId);
            
            if (battle == null) {
                // 发送离开失败响应
                sendLeaveBattleResponse(ctx, false, "Not in any battle");
                return false;
            }
            
            // 将玩家从战斗中移除
            enhancedBattleSessionManager.removePlayerFromBattle(userId);
            
            // 发送离开成功响应
            sendLeaveBattleResponse(ctx, true, "Left battle successfully");
            logger.info("Player {} left battle: {}", userId, battle.getBattleId());
            return true;
        } catch (Exception e) {
            logger.error("Error handling leave battle message for user: " + userId, e);
            sendLeaveBattleResponse(ctx, false, "Error leaving battle");
            return false;
        }
    }
    
    /**
     * 处理开始战斗消息
     */
    public boolean handleStartBattle(ChannelHandlerContext ctx, Long userId, int messageId, byte[] messageData) {
        try {
            // 获取用户所在的战斗
            BattleInfo battle = enhancedBattleSessionManager.getUserBattleInfo(userId);
            
            if (battle == null) {
                // 发送开始失败响应
                sendStartBattleResponse(ctx, false, "Not in any battle");
                return false;
            }
            
            // 检查战斗状态
            if (battle.getStatus() != BattleInfo.BattleStatus.WAITING) {
                // 发送开始失败响应
                sendStartBattleResponse(ctx, false, "Battle is not in waiting state");
                return false;
            }
            
            // 开始战斗
            boolean success = enhancedBattleSessionManager.startBattle(battle.getBattleId());
            
            if (success) {
                // 发送开始成功响应
                sendStartBattleResponse(ctx, true, "Battle started successfully");
                logger.info("Player {} started battle: {}", userId, battle.getBattleId());
                return true;
            } else {
                // 发送开始失败响应
                sendStartBattleResponse(ctx, false, "Failed to start battle");
                logger.warn("Player {} failed to start battle: {}", userId, battle.getBattleId());
                return false;
            }
        } catch (Exception e) {
            logger.error("Error handling start battle message for user: " + userId, e);
            sendStartBattleResponse(ctx, false, "Error starting battle");
            return false;
        }
    }
    
    /**
     * 处理非战斗相关消息
     */
    public boolean handleNonBattleMessage(ChannelHandlerContext ctx, int messageId, byte[] messageData, Long userId) {
        // 检查是否是战斗创建消息，创建战斗时还没有battleId
        if (messageId == CREATE_BATTLE && userId != null) {
            return handleCreateBattle(ctx, userId, messageId, messageData);
        }
        
        // 检查是否是加入战斗消息，可能还没有获取到battleId
        if (messageId == JOIN_BATTLE && userId != null) {
            return handleJoinBattle(ctx, userId, null, messageId, messageData);
        }
        
        // 检查是否是离开战斗消息，可能还没有获取到battleId
        if (messageId == LEAVE_BATTLE && userId != null) {
            return handleLeaveBattle(ctx, userId, messageId, messageData);
        }
        
        // 检查是否是开始战斗消息，可能还没有获取到battleId
        if (messageId == START_BATTLE && userId != null) {
            return handleStartBattle(ctx, userId, messageId, messageData);
        }
        
        // 不是非战斗消息或无法处理
        return false;
    }
    
    // 辅助方法：从消息中提取字符串（示例实现）
    private String extractStringFromMessage(byte[] messageData, int offset) {
        try {
            if (messageData.length <= offset) {
                return null;
            }
            
            // 读取字符串长度（假设前4字节是长度）
            int length = 0;
            for (int i = 0; i < 4 && offset + i < messageData.length; i++) {
                length |= (messageData[offset + i] & 0xff) << (8 * i);
            }
            
            // 检查长度是否有效
            if (length <= 0 || offset + 4 + length > messageData.length) {
                return null;
            }
            
            // 读取字符串内容
            byte[] stringBytes = new byte[length];
            System.arraycopy(messageData, offset + 4, stringBytes, 0, length);
            return new String(stringBytes, "UTF-8");
        } catch (Exception e) {
            logger.error("Error extracting string from message", e);
            return null;
        }
    }
    
    // 辅助方法：从消息中提取整数（示例实现）
    private Integer extractIntFromMessage(byte[] messageData, int offset) {
        try {
            if (messageData.length < offset + 4) {
                return null;
            }
            
            int value = 0;
            for (int i = 0; i < 4; i++) {
                value |= (messageData[offset + i] & 0xff) << (8 * i);
            }
            return value;
        } catch (Exception e) {
            logger.error("Error extracting int from message", e);
            return null;
        }
    }
    
    // 以下为发送响应消息的方法，实际实现中应该根据具体的消息协议进行调整
    
    private void sendCreateBattleResponse(ChannelHandlerContext ctx, long battleId, boolean success, String message) {
        // 实际实现中应该构造并发送创建战斗响应消息
        logger.info("Sending create battle response: battleId={}, success={}, message={}", 
                   battleId, success, message);
    }
    
    private void sendJoinBattleResponse(ChannelHandlerContext ctx, boolean success, String message) {
        // 实际实现中应该构造并发送加入战斗响应消息
        logger.info("Sending join battle response: success={}, message={}", success, message);
    }
    
    private void sendLeaveBattleResponse(ChannelHandlerContext ctx, boolean success, String message) {
        // 实际实现中应该构造并发送离开战斗响应消息
        logger.info("Sending leave battle response: success={}, message={}", success, message);
    }
    
    private void sendStartBattleResponse(ChannelHandlerContext ctx, boolean success, String message) {
        // 实际实现中应该构造并发送开始战斗响应消息
        logger.info("Sending start battle response: success={}, message={}", success, message);
    }
}